<?php

namespace app\controller\mobile;

use app\common\model\Admin;
use app\common\service\UserService;
use app\common\util\Result;
use think\annotation\route\Group;
use think\annotation\route\Post;
use think\annotation\route\Route;
use think\facade\Request;

#[Group('mobile/auth')]
class AuthController extends MobileBaseController
{
    const LOGIN_VALIDATE = [
        'phone|手机号' => 'require|length:11',
        'password|密码' => 'require|max:50'
    ];

    #[Post('login')]
    public function login()
    {
        ['phone' => $phone, 'password' => $password] = $param = \request()->param();
        $this->validate($param, self::LOGIN_VALIDATE);

        $service = new UserService(app());
        $this->getKey();

        $res = $service->login($phone, $password, $this->getKey());
        return Result::json($res);
    }

    #[Route('GET|POST', 'register')]
    public function register()
    {
        $rule = [
            'phone|手机号' => 'require|number|length:11',
            'password|密码' => 'require|max:50'
        ];
        ['phone' => $phone, 'password' => $password] = $param = \request()->param();
        $this->validate($param, $rule);
        $service = new UserService(app());
        $res = $service->register($param);
        if ($res["code"] != 0) {
            return Result::json($res);
        }
        $loginRes = $service->login($phone, $password, $this->getKey());
        if($loginRes["code"]!=0){
            return Result::json($loginRes);
        }
        return Result::rest($loginRes["data"]);
    }
}
